package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 未支付订单超时自动取消
     */
    @Scheduled(cron = "0 * * * * ?")
    public void autoCancel(){
        log.info("自动取消订单：{}", LocalDateTime.now());
        List<Orders> target = orderMapper.getByStatusAndOrderTimeLt(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        if(Collections.isEmpty(target)){
            return;
        }
        for (Orders update : target) {
            update.setStatus(Orders.CANCELLED);
            update.setCancelTime(LocalDateTime.now());
            update.setCancelReason("订单超时自动取消");
            orderMapper.update(update);
        }
    }

    /**
     * 派送中订单自动完成
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void autoComplete(){
        log.info("定时处理派送中订单：{}", LocalDateTime.now());
//        List<Orders> targets = orderMapper.getByStatus(Orders.DELIVERY_IN_PROGRESS);
        List<Orders> targets = orderMapper.getByStatusAndOrderTimeLt(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusHours(1));
        if (Collections.isEmpty(targets)) {
            return;
        }
        for (Orders update : targets) {
            update.setStatus(Orders.COMPLETED);
//            update.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(update);
        }
    }
}
